﻿function getProblemListPanel() {
	var pageSize = 20;
	var showPreview = window.screen.width > 800;

	var store = new Ext.data.Store({
				proxy : new Ext.data.HttpProxy({
							url : url.getProblemList
						}),
				reader : new Ext.data.JsonReader({
							root : 'result',
							totalProperty : 'total',
							id : 'pid'
						}, ['pid', 'title', 'description', 'accept', 'submit',
								'status'])
			});
	store.load({
				params : {
					start : 0,
					limit : pageSize
				}
			});

	var cm = new Ext.grid.ColumnModel([{
				header : 'Problem Title',
				sortable : false,
				dataIndex : 'title',
				renderer : titleFormat
			}, {
				header : 'Statistics',
				sortable : false,
				dataIndex : 'submit',
				width : 30,
				renderer : ratioFormat
			}]);

	var sm = new Ext.grid.RowSelectionModel({
				singleSelect : true
			});

	var toolbar = new Ext.Toolbar({
				items : [new Ext.Button({
									text : '刷新',
									iconCls : 'refresh-icon',
									handler : function() {
										store.reload();
									}
								}), new Ext.Button({
									text : '预览',
									iconCls : 'preview-icon',
									enableToggle : true,
									pressed : showPreview,
									toggleHandler : function(sender, pressed) {
										showPreview = pressed;
										grid.view.refresh();
									}
								}), new Ext.Toolbar.Separator(),
						new Ext.Button({
									text : '统计',
									iconCls : 'statistics-icon',
									disabled : true,
									handler : onStatistics
								}), new Ext.Button({
									text : '查看',
									iconCls : 'problemlist-icon',
									disabled : true,
									handler : onShowProblem
								})]
			});

	var godbuttons;
	if (sys.god) {
		godbuttons = [new Ext.Toolbar.Separator(), new Ext.Button({
							text : '添加',
							iconCls : 'add-icon',
							handler : function() {
								addOrEditProblem();
							}
						}), new Ext.Button({
							text : '编辑',
							iconCls : 'edit-icon',
							handler : onEdit,
							disabled : true
						}), new Ext.Button({
							text : '删除',
							iconCls : 'delete-icon',
							handler : onDelete,
							disabled : true
						}), new Ext.Toolbar.Separator(), new Ext.Button({
							text : '重判代码',
							iconCls : 'rejudge-icon',
							handler : onRejudgeStatus,
							disabled : true
						}), new Ext.Button({
							text : '删除代码',
							iconCls : 'clean-icon',
							handler : onCleanStatus,
							disabled : true
						})];
		toolbar.add(godbuttons);
	}

	var txtpid = new Ext.form.NumberField({
				width : 50,
				style : 'text-align:center',
				emptyText : 'PID',
				allowDecimals : false,
				allowNegative : false,
				enableKeyEvents : true,
				selectOnFocus : true
			});
	txtpid.on('keypress', function(t, e) {
				if (e.getKey() == e.ENTER) {
					btnfind.focus();
					onfind();
				}
			})
	var btnfind = new Ext.Button({
				text : '转到',
				iconCls : 'goto-icon',
				handler : onfind
			});

	var pagebar = new Ext.PagingToolbar({
				pageSize : pageSize,
				store : store,
				displayInfo : true,
				emptyMsg : '当前没有题目。',
				displayMsg : '当前显示第 {0} - {1} 题，共 {2} 题。',
				items : [new Ext.Toolbar.Spacer({
									width : 5
								}), txtpid, btnfind],
				plugins : new Ext.ux.SlidingPager()
			});

	var grid = new Ext.grid.GridPanel({
				title : 'Problems',
				iconCls : 'problemlist-icon',
				closable : false,
				region : 'center',
				loadMask : {
					msg : '载入中...'
				},
				viewConfig : {
					forceFit : true,
					enableRowBody : true,
					showPreview : showPreview,
					getRowClass : previewFormat,
					scrollToRow : function(rowIndex) {
						var firstRow = Ext.get(this.getRow(0));
						var row = Ext.get(this.getRow(rowIndex));
						var distance = row.getOffsetsTo(firstRow)[1];
						this.scroller.dom.scrollTop = distance;
					}
				},
				store : store,
				cm : cm,
				sm : sm,
				tbar : toolbar,
				bbar : pagebar,
				listeners : {
					'beforeclose' : function() {
						return false;
					}
				}
			});
	sm.on('selectionchange', onSelect);
	grid.on('rowdblclick', onShowProblem);

	return grid;

	function titleFormat(value, p, record) {
		if (showPreview)
			return String
					.format(
							'<div class="{2}" style="height:16px">{0}.&nbsp; '
									+ '<a href="javascript:void(0);" onclick="showProblem({0});" class="likelink" style="color:black;font-weight:bold">{1}</a>'
									+ '<br />', record.data.pid, value,
							['problem-icon', 'solving-icon', 'accepted-icon',
									'hidden-icon'][record.data.status]);
		return String
				.format(
						'<div class="{2}" style="height:16px">{0}.&nbsp; '
								+ '<a href="javascript:void(0);" onclick="showProblem({0});" class="likelink" style="color:black;font-weight:bold">{1}</a>',
						record.data.pid, value,
						['problem-icon', 'solving-icon', 'accepted-icon',
								'hidden-icon'][record.data.status]);
	}
	function ratioFormat(value, p, record) {
		if (showPreview)
			return String
					.format(
							'{0} / {1}<br /><div>(<span class="ratio-text"> {2} </span>)</div>',
							record.data.accept, value, sys.rd.ratio(
									record.data.accept, value));
		return String.format(
				'{0} / {1}&nbsp; (<span class="ratio-text"> {2} </span>)',
				record.data.accept, value, sys.rd.ratio(record.data.accept,
						value));
	}
	function previewFormat(record, rowIndex, p) {
		if (showPreview) {
			p.body = String.format('<p>{0}</p>', Ext.util.Format
							.trim(Ext.util.Format
									.stripTags(record.data.description.replace(
											/&nbsp;/g, ' ')))
							.gbtrim(window.screen.width > 800 ? 120 : 60));
			return 'x-grid3-row-expanded';
		}
		return 'x-grid3-row-collapsed';
	}

	function onEdit() {
		var select = getSelect();
		if (!select)
			return;
		addOrEditProblem(select.data.pid);
	}
	function onDelete() {
		var select = getSelect();
		if (!select)
			return;
		deleteProblem({
					pid : select.data.pid,
					title : select.data.title
				});
	}
	function onRejudgeStatus() {
		var select = getSelect();
		if (!select)
			return;
		rejudgeProblemStatus({
					pid : select.data.pid,
					title : select.data.title
				});
	}
	function onCleanStatus() {
		var select = getSelect();
		if (!select)
			return;
		cleanProblemStatus({
					pid : select.data.pid,
					title : select.data.title
				});
	}

	function getSelect() {
		if (sm.getCount() == 0)
			return null;
		return sm.getSelected();
	}
	function onSelect() {
		var record = getSelect();
		var disable = !record;
		toolbar.get(3).setDisabled(disable);
		toolbar.get(4).setDisabled(disable);

		if (sys.god) {
			godbuttons[2].setDisabled(disable);
			godbuttons[3].setDisabled(disable);
			godbuttons[5].setDisabled(disable);
			godbuttons[6].setDisabled(disable);
		}
	}
	function onShowProblem() {
		var record = getSelect();
		if (!record)
			return;
		showProblem(record.data.pid);
	}
	function onStatistics() {
		var record = getSelect();
		if (!record)
			return;
		showProblemStatistics(record.data.pid);
	}
	function onfind() {
		if (Ext.isEmpty(txtpid.getValue()))
			return;
		getPIDPoint({
					pid : txtpid.getValue(),
					success : function(obj) {
						store.load({
									params : {
										start : obj.point - obj.point
												% pageSize,
										limit : pageSize
									},
									callback : function() {
										sm.selectRow(obj.point % pageSize);
										new Ext.util.DelayedTask(function() {
													grid
															.getView()
															.scrollToRow(obj.point
																	% pageSize);
												}).delay(300);
										txtpid.reset();
									}
								});
					}
				});
	}
}

function refreshProblemList(page) {
	var grid = ui.problemList;
	var store = grid.getStore();
	if (page) {
		var pageSize = grid.bbar.pageSize;
		store.load({
					params : {
						start : pageSize * (page - 1),
						limit : pageSize
					}
				});
	} else
		store.reload();
}

function deleteProblem(obj) {
	obj = defaultx(obj, 'pid');
	confirmx('您确定要删除题目 '
					+ (obj.title
							? '<br />' + obj.pid + ' - ' + obj.title
							: ' - ' + obj.pid) + ' 吗？<br />该题的所有状态也会被一并删除！',
			function() {
				ajax({
							url : url.deleteProblem,
							params : {
								pid : obj.pid
							},
							success : function() {
								refreshProblemList();
								if (obj.success)
									obj.success();
							}
						});
			});
}

function rejudgeProblemStatus(obj) {
	obj = defaultx(obj, 'pid');
	confirmx('您确定要重判题目 '
					+ (obj.title
							? '<br />' + obj.pid + ' - ' + obj.title
							: ' - ' + obj.pid)
					+ '<br />的所有代码吗？<br />该题的所有统计都会被重计。', function() {
				ajax({
							url : url.rejudgeProblemStatus,
							params : {
								pid : obj.pid
							},
							success : function() {
								alertx('服务器接受了请求，代码正在重判...');
								refreshProblemList();
								showStatusList({
											pid : obj.pid
										});
								if (obj.success)
									obj.success();
							}
						});
			});
}

function cleanProblemStatus(obj) {
	obj = defaultx(obj, 'pid');
	confirmx('您确定要清除题目 '
					+ (obj.title
							? '<br />' + obj.pid + ' - ' + obj.title
							: ' - ' + obj.pid)
					+ '<br />的所有状态吗？<br />该题的所有统计都会被重置。', function() {
				ajax({
							url : url.cleanProblemStatus,
							params : {
								pid : obj.pid
							},
							success : function() {
								alertx('状态已全部清除。');
								refreshProblemList();
								if (obj.success)
									obj.success();
							}
						});
			});
}

function getPIDPoint(obj) {
	ajax({
				url : url.getPIDPoint,
				params : {
					pid : obj.pid
				},
				success : obj.success
			});
}
